package com.example.grape_effect.effet.effect

import com.example.grape_effect.effet.effect.LYEffect
import com.example.grape_effect.gl.common.ShaderParameter

class WhirlpoolEffect: LYEffect() {
    override var fragmentShader =
        """ varying highp vec2 textureCoordinate;
uniform sampler2D inputTexture;
//const float _distanceFactor = 0.1;

uniform float rotation ;
const vec2 center = vec2(0.5, 0.5);
void main(){

    highp vec2 dir = textureCoordinate - center  ;
    //计算旋转的角度：对于像素点来说，距离中心越远，旋转越少，所以除以距离。相当于用DistortFactor作为旋转的角度值Distort/180 * π，π/180 = 0.1745
    float rot = rotation * 0.1745 / (length(dir) + 0.001);//+0.001防止除零
    float sinval = sin(rot);
    float cosval = cos(rot);
    mat2 rotateMatrix = mat2(cosval, -sinval, sinval, cosval);
    dir = dir * rotateMatrix ;
    dir += center.xy;
//    vec2 uv = textureCoordinate + dir;
    gl_FragColor = texture2D(inputTexture, dir);
}

"""

    init{
        name = "whirlpoolEffect"
        duration = 2000L
    }
    override fun addParameters() {
        super.addParameters()
        parameters["rotation"] = ShaderParameter(
            "rotation",
            ShaderParameter.TYPE_UNIFORM,
            ShaderParameter.VALUE_TYPE_FLOAT
        )
    }

    override fun setDefaultParameterValues() {
        super.setDefaultParameterValues()
        parameters["rotation"]?.value =0f

    }

    var rotation = 0f
    fun updateRotation(executeTime:Long) {
        val time = executeTime.toFloat() % 3000
        rotation = if (time < duration/2) {
            time / 100
        } else if (time < duration) {
            (duration - time)/100
        } else {
            0f
        }
        parameters["rotation"]?.value = rotation
    }

    // must use in glThread
    override fun draw() {
        updateRotation(System.currentTimeMillis() - startTime)
        super.draw()
    }
}
/****** shader 解释说明
//平移坐标点到中心点,同时也是当前像素点到中心的方向
fixed2 dir = i.uv - _DistortCenter.xy;
//计算旋转的角度：对于像素点来说，距离中心越远，旋转越少，所以除以距离。相当于用DistortFactor作为旋转的角度值Distort/180 * π，π/180 = 0.1745
float rot = _DistortFactor * 0.1745 / (length(dir) + 0.001);//+0.001防止除零
//计算sin值与cos值，构建旋转矩阵
fixed sinval, cosval;
sincos(rot, sinval, cosval);
float2x2  rotmatrix = float2x2(cosval, -sinval, sinval, cosval);
//旋转
dir = mul(dir, rotmatrix);
//再平移回原位置
dir += _DistortCenter.xy;
//采样noise图
fixed4 noise = tex2D(_NoiseTex, i.uv);
//noise的权重 = 参数 * 距离，越靠近外边的部分，扰动越严重
float2 noiseOffset = noise.xy * _DistortStrength * dir;
//用偏移过的uv+扰动采样MainTex
return tex2D(_MainTex, dir + noiseOffset);
 *******************/